<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Weixin\Controller;
use Think\Controller;

/**
 * 前台公共控制器
 * 为防止多分组Controller名称冲突，公共Controller名称统一使用分组名称
 */
class WeixinController extends Controller {
    public $uid = 0;
    public $appid       = 'wx8f2d665a3f974eaa';
    public $appsecret   = 'e28c5413a4d46bb70e63ce250c530fc1';
    public $token       = 'alisytcom';
    public $weixin      = '';
    public $access_token = '';
    public $openid      = '';
    /* 空操作，用于输出404页面 */
    public function _empty(){
        $this->redirect('Index/index');
    }

    //https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET  $url='',$vars='',$suffix=true,$domain=false
    protected function oauth(){
        $geturl = get_url();
        cookie('LoginGetUrl',$geturl,60);
        $url = U('User/UserLoginOauth','',true,true);
        $url = $this->weixin->getOauthRedirect($url);
        header('Location: ' . $url);
    }

    protected function _initialize(){
        header('Content-Type:application/json; charset=utf-8');
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Max-Age:86400'); // 允许访问的有效期
        header('Access-Control-Allow-Headers:*');
        header('Access-Control-Allow-Methods:OPTIONS, GET, POST, DELETE');

        //require_once('ThinkPHP/Library/Vendor/api_payment/llpaypayment.php');
        require_once('ThinkPHP/Library/Vendor/OCR_API.php');


        /* 读取站点配置 */
        $config = api('Config/lists');
        C($config); //添加配置
        if(!C('WEB_SITE_CLOSE')){
            $this->error('站点已经关闭，请稍后访问~');
        }  
        $options = array(
            'token'     => $this->token,   // 填写你设定的key
            'appid'     => $this->appid,    // 填写高级调用功能的appid
            'appsecret' => $this->appsecret // 填写高级调用功能的密钥
        );
        $this->weixin = new \Common\Extend\Wechat\Wechat($options);
        $weixin = cookie('WeixinLogin');


        if(empty($weixin)){
            $this->oauth();   //调用了微信的OAuth2.0授权，设置为仅在微信打开
        }else{
            // $this->uid          = $weixin['uid'];

            //存入redis
//            $client = new \Predis\Client(C('REDIS'));
//            $key = "wxuser:".$weixin['uid']."info";
//            $client->hmset($key,[
//                'wx_uid' => $weixin['uid'],
//                'access_token' => $weixin['access_token'],
//                'openid' => $weixin['openid'],
//            ]);

            $this->wx_uid       = $weixin['uid'];
            $this->access_token = $weixin['access_token'];
            $this->openid       = $weixin['openid'];
        }  


        $c=CONTROLLER_NAME;
        $a=ACTION_NAME;

        


        $re1= ($c=='Koubei'&&($a=='login'||$a=='yonghu2'||$a=='yonghu'||$a=='get_code'||$a=='zc_code'||$a=='zc_code2'||$a=='send_post'||$a=='forget'||$a=='tgm_band'||$a=='verify'||$a=='verify2'||$a=='test'||$a=='cookie' || $a == 'get_user_td_rate'));
        $re2= ($c=='Service'&&($a=='youka_return'||$a='curl_send_post'));
        // print_r($_SESSION);die;
        if($re1||$re2){

        }else{

//            if(!empty($_COOKIE['user'])){
//                $uid=$_COOKIE['user']['uid'];
//                    $one=D('Ptyh')->where(['uid'=>$uid])->find();
//                    if(md5($one['account'])==$_COOKIE['user']['account'] && $_COOKIE['user']['login']==1 ){
//                        $this->uid = $_COOKIE['user']['uid'];
//                    }else{
//                        echo "<script>location.href='http://hbxyk.hihaoge.me/index.php?m=Weixin&c=Koubei&a=login'</script>";die;
//                    }
//
//                    // $this->cookie('user',$_SESSION['user'],time()+3600*24*7);
//            }else{
//
//                    // if(($this->wx_uid!=33)&&($this->wx_uid!=31)&&($this->wx_uid!=615)&&($this->wx_uid!=639)){
//                    //     echo '<font style="color:red;font-size:40px;">系统维护中~</font>';die;
//                    // }else{
//                        echo "<script>location.href='http://hbxyk.hihaoge.me/index.php?m=Weixin&c=Koubei&a=login'</script>";die;
//                    // }
//            }
        }
        


        
    }

    // function cookie($var, $value='', $time=0, $path='', $domain=''){
    //     $_COOKIE[$var] = $value;
    //     if(is_array($value)){
    //         foreach($value as $k=>$v){
    //             setcookie($var.'['.$k.']', $v, $time, $path, $domain, $s);
    //         }
    //     }else{
    //         setcookie($var, $value, $time, $path, $domain, $s);
    //     }
    // }



    /* 用户登录检测 */
    protected function login(){
        /* 用户登录检测 */
        is_login() || $this->error('您还没有登录，请先登录！', U('User/login'));
    } 

     protected function lists ($model,$where=array(),$order='',$base = array('status'=>array('egt',0)),$field=true){
        $options    =   array();
        $REQUEST    =   (array)I('request.');
        if(is_string($model)){
            $model  =   M($model);
        }

        $OPT        =   new \ReflectionProperty($model,'options');
        $OPT->setAccessible(true);

        $pk         =   $model->getPk();
        if($order===null){
            //order置空
        }else if ( isset($REQUEST['_order']) && isset($REQUEST['_field']) && in_array(strtolower($REQUEST['_order']),array('desc','asc')) ) {
            $options['order'] = '`'.$REQUEST['_field'].'` '.$REQUEST['_order'];
        }elseif( $order==='' && empty($options['order']) && !empty($pk) ){
            $options['order'] = $pk.' desc';
        }elseif($order){
            $options['order'] = $order;
        }
        unset($REQUEST['_order'],$REQUEST['_field']);

        $options['where'] = array_filter(array_merge( (array)$base, /*$REQUEST,*/ (array)$where ),function($val){
            if($val===''||$val===null){
                return false;
            }else{
                return true;
            }
        });
        if( empty($options['where'])){
            unset($options['where']);
        }
        $options      =   array_merge( (array)$OPT->getValue($model), $options );
        $total        =   $model->where($options['where'])->count();

        if( isset($REQUEST['r']) ){
            $listRows = (int)$REQUEST['r'];
        }else{
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        if($total>$listRows){
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p =$page->show();
        $this->assign('_page', $p? $p: '');
        $this->assign('_total',$total);
        $options['limit'] = $page->firstRow.','.$page->listRows;

        $model->setProperty('options',$options);

        return $model->field($field)->select();
    }







    function curl_send_post($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return json_decode($res,true);
    }
     

}
